package com.epfresh.fragment;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AccelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.epfresh.R;
import com.epfresh.activity.*;
import com.epfresh.activity.DcStoreActivity;
import com.epfresh.activity.GoodsListActivity;
import com.epfresh.activity.HomeActivity;
import com.epfresh.activity.HomePreActivity;
import com.epfresh.activity.HomeSecondAreaActivity;
import com.epfresh.activity.ListStoreActivity;
import com.epfresh.activity.LoginActivity;
import com.epfresh.activity.MyOrderActivity;
import com.epfresh.activity.ReceiverAddressActivity;
import com.epfresh.activity.WebActivity;
import com.epfresh.adapter.ViewBinderHomeAd;
import com.epfresh.adapter.ViewBinderHomeBanner;
import com.epfresh.adapter.*;
import com.epfresh.adapter.ViewBinderHomeViewPager;
import com.epfresh.api.entity.*;
import com.epfresh.api.global.AppActivity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.AppUtils;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.basedialog.CustomDialog;
import com.epfresh.basedialog.CustomDialogRedBag;
import com.epfresh.bean.Ad;
import com.epfresh.bean.HomeTop;
import com.epfresh.bean.HomeTopBean;
import com.epfresh.bean.*;
import com.epfresh.bean.TypeBean;
import com.epfresh.constant.Constant;
import com.epfresh.global.BaseFragment;
import com.epfresh.global.CartHelper;
import com.epfresh.global.DataManager;
import com.epfresh.guider.HighLightGuideView;
import com.epfresh.utils.FileCache;
import com.epfresh.utils.FormatUtil;
import com.epfresh.views.FakeAddImageView;
import com.epfresh.views.HomeCountDownView;
import com.epfresh.views.PointFTypeEvaluator;
import com.epfresh.views.dialog.MsgDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import multitype.MultiTypeAdapter;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

import  com.epfresh.api.widget.tablayout.listener.*;

/**
 * Created by wzh on 16-7-1.
 */
public class TopFragmentRecycler extends BaseFragment implements HomeCountDownView.OnCountDownListener,OnTabSelectListener {

    private PtrFrameLayout ptrFrameLayout;

    MultiTypeAdapter multiAdapter;
    CustomGridLayoutManager layoutManager;
    private List<Object> items = new ArrayList<>();
    private RecyclerView lvMarket;
    LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();
    ViewBinderHomeOftenOffer viewBinderHomeOftenOffer;

    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();
            Log.e("onLoadMore",""+oftenPage);
            mHttpOftenLoad(oftenPage + 1,false);
        }
    };
    public void showGoCartRed(boolean flag,boolean netFlag){
        if(oftenTitle!=null&&items!=null) {
            oftenTitle.setHasRedRound(flag);
            Log.e("showGoCartRed","___"+flag);
            multiAdapter.notifyItemChanged(items.indexOf(oftenTitle));
            //mHttpOftenLoad(0,false);
            if(netFlag)
                requestCount();
        }
    }

    int tabPosition = 0;
    @Override
    public void onTabSelect(int i) {
        topCategoryId = homeGoodsOften.getTopCategory().get(i).getId();
        tabPosition = i;
        Log.e("tabPosition",""+i);
        //multiAdapter.notifyItemChanged(items.indexOf(homeGoodsOften));
        showProgressDialog();
        mHttpOftenLoad(0,false);
    }

    @Override
    public void onTabReselect(int i) {

    }

    PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvMarket, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            mHttpLoad();
        }
    };

    @Override
    public String getBaseTag() {
        return "topFragment";
    }

/*    @Override
    public void onResume() {
        super.onResume();
        Log.e("refresh","fresh often");
        if(DataManager.getInstance().oftenListReFresh){
            mHttpOftenLoad(0,false);
        }
    }*/

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_top_recycler,
                container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews(view);
        initCartView();
        //mHttpLoad();
    }


    public Timer timer;
    boolean isTimerAlive;
    TimerTask task ;
    Handler handler = new Handler(){

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    multiAdapter.notifyDataSetChanged();
                    break;
            }
            super.handleMessage(msg);
        }

    };

    public void timerStart() {
        timerStop();
        if(timer == null)
            timer = new Timer();

        task =  new TimerTask() {
            @Override
            public void run() {
                try {
                    if (isTimerAlive){
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        isTimerAlive = true;

        timer.schedule(task, 0, 1000);
    }


    public void timerStop() {
        isTimerAlive = false;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null){
            task.cancel();
            task = null;
        }
    }




    void initViews(View view){

        ptrFrameLayout = (PtrMdFrameLayout) view.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
        vTips = view.findViewById(R.id.v_tips);
        int w = LocalDisplay.SCREEN_WIDTH_PIXELS;
        int h;
        if(bannerShow)
            h = w * 405 / 1080;
        else
            h = 0;
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) vTips.getLayoutParams();
        lp.topMargin = h;
        vTips.setLayoutParams(lp);
        lvMarket = (RecyclerView) view.findViewById(R.id.lv_market);
/*        lvMarket.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                Log.e("1111",motionEvent.getAction()+""+"___isVis"+isTipsVisible);
                if(motionEvent.getAction() == MotionEvent.ACTION_UP&&isTipsVisible){
                    Log.e("__________","抬起");
                    ptrFrameLayout.refreshComplete();
                    lvMarket.scrollToPosition(0);
                }
                return false;
            }
        });*/
        lvMarket.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                /*
                new State
                0（SCROLL_STATE_IDLE）表示recyclerview是不动的（The RecyclerView is not currently scrolling.）
                1（SCROLL_STATE_DRAGGING）表示recyclerview正在被拖拽（The RecyclerView is currently being dragged by outside input such as user touch input.）
                2（SCROLL_STATE_SETTLING）表示recyclerview正在惯性下滚动（The RecyclerView is currently animating to a final position while not under outside control.）
                 */
                switch(newState)
                {
                    case 0:
                        if(isTipsVisible) {
                            System.out.println("recyclerview已经停止滚动");
                            Log.e("__________", "recyclerview已经停止滚动");
                            ptrFrameLayout.refreshComplete();
                            lvMarket.scrollToPosition(0);
                        }
                        break;
                    case 1:
                        //System.out.println("recyclerview正在被拖拽");
                        break;
                    case 2:
                        //System.out.println("recyclerview正在依靠惯性滚动");
                        break;
                }
            }
        });





        multiAdapter = new MultiTypeAdapter();

        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        loadMoreViewBinder.setResourceId(R.layout.home_often_view_load_more);
        loadMoreDelegate.attach(lvMarket, loadMoreSubject);

        multiAdapter.register(LoadMoreItem.class, loadMoreViewBinder);

        multiAdapter.register(HomeTopBean.class, new ViewBinderHomeBanner());//banner 滚动广告条
        ViewBinderHomeViewPager viewBinderHomeViewPager = new ViewBinderHomeViewPager(getContext());
        viewBinderHomeViewPager.setOnItemClickListener(this);
        multiAdapter.register(LinkedList.class, viewBinderHomeViewPager);//配送中心，订单等功能条；

        ViewBinderHomeSecond viewBinderHomeSecond = new ViewBinderHomeSecond();
        viewBinderHomeSecond.setCountDownListener(this);

        ViewBinderHomeSecondOnlyOne viewBinderHomeSecondOne = new ViewBinderHomeSecondOnlyOne();
        viewBinderHomeSecondOne.setCountDownListener(this);
        multiAdapter.register(HomeTop.SeckillBeanX.SeckillBean.class, viewBinderHomeSecond);//秒杀
        multiAdapter.register(HomeTopBean.SecondsOne.class, viewBinderHomeSecondOne);//秒杀
        multiAdapter.register(Ad.class, new ViewBinderHomeAd());//广告
/*        multiAdapter.register(HomeTopBean.GoodsOne.class, new ViewBinderHomeGoodsOne());//单图商品条
        multiAdapter.register(HomeTopBean.GoodsMore.class, new ViewBinderHomeGoodsMore());//多图商品条目*/
/*
        multiAdapter.register(Integer.class, new ViewBinderHomeBottom());//结束条
*/
/*        multiAdapter.register(HomeTopBean.StoreOne.class, new ViewBinderHomeStoreOne());//单图店铺条
        multiAdapter.register(HomeTopBean.StoreMore.class, new ViewBinderHomeStoreMore());//多图店铺条目*/

        ViewBinderHomeOftenTitle viewBinderHomeOftenTitle =  new ViewBinderHomeOftenTitle();
//        viewBinderHomeOftenTitle.context = this;todo
        multiAdapter.register(OftenTitle.class, viewBinderHomeOftenTitle);//结束条

        ViewBinderHomeOftenCategory viewBinderHomeOftenCategory = new ViewBinderHomeOftenCategory();
        viewBinderHomeOftenCategory.setOnRecyclerViewItemClickListener(this);
        multiAdapter.register(HomeGoodsOften.class, viewBinderHomeOftenCategory);//结束条

        if(viewBinderHomeOftenOffer==null)
            viewBinderHomeOftenOffer = new ViewBinderHomeOftenOffer();
//        viewBinderHomeOftenOffer.context = this;todo

        viewBinderHomeOftenOffer.setOnCartAddListener(new ViewBinderHomeOftenOffer.OnCartAddListener() {
            @Override
            public void onCartAdd(int type, int position, HomeGoodsOften.ContentBean goods, View v) {
                if (type == 1) {//购物车手动输入
                    openDialog(goods);
                } else if (type == 2) {//添加
                    addCartCnt(v, goods, true);
                } else if (type == 3) {//减少
                    addCartCnt(v, goods, false);
                } else if (type == 5) {
                    if(goods.isDisabled())
                        return;
                    String id = goods.getId();
                    Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                    intent.putExtra("id", id + "");
                    intent.putExtra("storeId",goods.getStoreId());
                    intent.putExtra("promotionItemId", goods.getPromotionItemId());
                    startActivity(intent);
                } else if (type == 0) {
                    if (items.get(position) instanceof HomeGoodsOften.ContentBean) {
                        items.remove(position);
                        requestDelete(goods);
                        multiAdapter.notifyDataSetChanged();
                        if (items != null) {
                            for (int i = 0; i < items.size(); i++) {
                                if (items.get(i) instanceof HomeGoodsOften.ContentBean) {
                                    return;
                                }
                            }
                        }
                        tabPosition = 0;
                        topCategoryId = "";
                        showProgressDialog();
                        mHttpOftenLoad(0, false);
                    } else {
                        return;
                    }

                } else if (type == 10) {

                    if (goods.getShoppingCarId() == null) {
                        Log.e("getShoppingCarId", "_____null___" + goods.getShoppingCarId());
                        return;
                    }
                    requestFastMerTagList(goods);
                    //openMsgDialog(goods, goods.getFastMessages());
                }
            }
        });

        multiAdapter.register(HomeGoodsOften.ContentBean.class, viewBinderHomeOftenOffer);//配送中心，订单等功能条；
/*        ViewBinderHomeOftenGoods viewBinderHomeOftenGoods = new ViewBinderHomeOftenGoods();
        multiAdapter.register(HomeGoodsOften.ContentBean.class, viewBinderHomeOftenGoods);//结束条*/
        layoutManager = new CustomGridLayoutManager(getContext(), 4);
        final GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                Object item = items.get(position);
                return (item instanceof TypeBean) ? 1 : 4;
            }
        };
        layoutManager.setSpanSizeLookup(spanSizeLookup);
        lvMarket.setLayoutManager(layoutManager);
        lvMarket.setAdapter(multiAdapter);
        multiAdapter.setItems(items);
        //multiAdapter.notifyDataSetChanged();

    }

    public void initFirst(View v) {
        int [] flag = new int[2];
        v.getLocationOnScreen(flag);
        Log.e("LocationOnScreen","diyige:"+flag[0]+"dierge:"+flag[1]);
        if(v.getId()==R.id.tv_home_often_compare){
            T.offerImageToast(getContext(),flag[1],flag[0],"每个商品可以向不同的\n三家店铺咨询价格",true);
        }else{
            //T.offerImageToast(getContext(),flag[1],flag[0],"对常购清单内的商品\n可以询问实时价",false);
            T.offerImageToast(getContext(),flag[1],flag[0],"问价记录都在这",false);
        }
    }

    OnRequestListener<HomeTopBean> onRequestListener = new OnRequestListener<HomeTopBean>() {
        @Override
        public HomeTopBean jsonToObj(String responseStr) {
            Log.e("ESD","常购商品列表responseStr="+responseStr);
            return new Gson().fromJson(responseStr, HomeTopBean.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            ptrFrameLayout.refreshComplete();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            ptrFrameLayout.refreshComplete();
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<HomeTopBean> response, Object tag) {
            String responseStr = response.getResponseStr();
            FileCache fileCache = new FileCache(ApplicationHelper.getAppApplication());
            fileCache.saveFile((fileCache.getCachePath() + "home.json"), responseStr);
            homeTopBean = response.getResponseElement();
            initModels(homeTopBean);
            Log.e("new perfect info","take");
            mHttpOftenLoad(0,false);
            isCompleted();
        }
    };
    HomeTopBean homeTopBean = new HomeTopBean();
    public void mHttpLoad() {
        RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_homepage_purchaser);
        requestEntity.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        requestEntity.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
        request(requestEntity, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_homepage_purchaser, onRequestListener);
    }
    OftenTitle oftenTitle = new OftenTitle();
    HomeGoodsOften homeGoodsOften = new HomeGoodsOften();
    OnRequestListener<HomeGoodsOften> onRequestOftenListener = new OnRequestListener<HomeGoodsOften>() {
        @Override
        public HomeGoodsOften jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, HomeGoodsOften.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            if(oftenPage==0) {
                int flag = items.indexOf(oftenTitle);
                for (int i = items.size(); i > flag; i--) {
                    items.remove(i - 1);
                }
                timerStop();
                oftenTitle.setHaveMore(ViewBinderHomeOftenTitle.OFTENNO);
                items.add(oftenTitle);
            }
           // items.add(0);
            multiAdapter.notifyDataSetChanged();
            ptrFrameLayout.refreshComplete();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            if(oftenPage==0) {
                int flag = items.indexOf(oftenTitle);
                for (int i = items.size(); i > flag; i--) {
                    items.remove(i - 1);
                }
                timerStop();

                oftenTitle.setHaveMore(ViewBinderHomeOftenTitle.OFTENNO);
                items.add(oftenTitle);
            }
            //items.add(0);
            multiAdapter.notifyDataSetChanged();
            ptrFrameLayout.refreshComplete();
        }

        @Override
        public void onStart(Object tag) {
            //showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<HomeGoodsOften> response, Object tag) {
            requestCount();
            homeGoodsOften = response.getResponseElement();
            User user = homeGoodsOften.getAccountInfo();
            if (user != null) {
                user.setAccess_token(getUser().getAccess_token());
                user.setAccountId(getUser().getAccountId());
                user.setPassword(getUser().getPassword());
                user.setTag(UUID.randomUUID().toString());
                updateUser(user);
            }
            ptrFrameLayout.refreshComplete();
            hideProgressDialog();
            Log.e("request___","add"+homeGoodsOften.getTopCategory().size()+"page:"+oftenPage);
            oftenTitle.setHasAsk(!response.getResponseElement().isAccountIsBindDc());
            viewBinderHomeOftenOffer.setDcFlag(response.getResponseElement().isAccountIsBindDc());
            if(response.getResponseElement().getShoppingCarCount()>0){
                oftenTitle.setHasRedRound(true);
            }else {
                oftenTitle.setHasRedRound(false);
            }

            if (homeGoodsOften!=null&&homeGoodsOften.getNumber() == 0) {
                if(homeGoodsOften.getContent()==null||homeGoodsOften.getContent().size()==0){
                    if(!"".equals(topCategoryId)) {
                        T.toast("该品类暂无商品，已为您刷新数据");
                        topCategoryId = "";
                        tabPosition = 0;
                        showProgressDialog();
                        mHttpOftenLoad(0,false);
                    }
                }
                if (homeGoodsOften != null && homeGoodsOften.getTopCategory() != null && homeGoodsOften.getTopCategory().size() > 0) {
                    int flag = items.indexOf(oftenTitle);
                    for (int i = items.size(); i > flag; i--) {
                        items.remove(i - 1);
                    }
                    oftenTitle.setHaveMore(ViewBinderHomeOftenTitle.OFTENHAVE);
                    items.add(oftenTitle);

/*                    if ((homeGoodsOften.getContent() != null && homeGoodsOften.getContent().size() > 0) || (homeGoodsOften.getContent() != null && homeGoodsOften.getContent().size() > 0))
                        items.add(ViewBinderHomeOftenTitle.OFTENHAVE);
                    else
                        items.add(ViewBinderHomeOftenTitle.OFTENNO);*/
                    for (int j = 0; j < homeGoodsOften.getTopCategory().size(); j++) {
                        homeGoodsOften.getTopCategory().get(j).setSelect(false);
                        if (topCategoryId.equals(homeGoodsOften.getTopCategory().get(j).getId())) {
                            tabPosition = j;
                        }
                    }
                    if (homeGoodsOften.getTopCategory().size() > tabPosition)
                        homeGoodsOften.getTopCategory().get(tabPosition).setSelect(true);
                    else
                        homeGoodsOften.getTopCategory().get(0).setSelect(true);

                    items.add(homeGoodsOften);
                    timerStart();

                    Log.e("homeGoodsOften___","add___"+homeGoodsOften.getTopCategory().size());
/*                    items.addAll(homeGoodsOften.getContent());
                    items.addAll(homeGoodsOften.getContent());*/
                } else {
                    int flag = items.indexOf(oftenTitle);
                    for (int i = items.size(); i > flag; i--) {
                        items.remove(i - 1);
                    }
                    oftenTitle.setHaveMore(ViewBinderHomeOftenTitle.OFTENNO);
                    items.add(oftenTitle);
                    timerStop();
                    multiAdapter.notifyDataSetChanged();
                    return;
                }
            }else {
/*                if (response != null && response.getResponseElement() != null && response.getResponseElement().getContent() != null)
                    items.addAll(response.getResponseElement().getContent());
                if (response != null && response.getResponseElement() != null && response.getResponseElement().getContent() != null)
                    items.addAll(response.getResponseElement().getContent());*/
            }
            ArrayList list = new ArrayList();

                if (response != null && response.getResponseElement() != null && response.getResponseElement().getContent() != null)
                    list.addAll(response.getResponseElement().getContent());
/*            if (response != null && response.getResponseElement() != null && response.getResponseElement().getContent() != null)
                list.addAll(response.getResponseElement().getContent());*/

            //loadMoreDelegate.setStatusEmpty();
            //loadMoreDelegate.addAllItem(items,arrayList);
            //if(items.indexOf())

            if (list.size() == 0) {
                loadMoreDelegate.setStatusNoMore();
            } else {
                loadMoreDelegate.addAllItem(items, list);
            }


/*            loadMoreDelegate.addLoadItemOnly(items);
            //最后一个*/
            if (response.getResponseElement().isLast()) {
                loadMoreDelegate.setStatusNoMore();
            } else {
                loadMoreDelegate.setStatusNormal();
            }

            multiAdapter.notifyDataSetChanged();

        }
    };
    int oftenPage=0;
    public void mHttpOftenLoad(int page,boolean homeFlag) {
        if(homeFlag==true){
            topCategoryId = "";
            tabPosition = 0;
        }
        oftenPage = page;
        RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_offen_oftenList);
        requestEntity.putParameter("topCategoryId", topCategoryId);
        requestEntity.putParameter("pageNumber",page);
        requestEntity.putParameter("pageSize", "10");
        requestEntity.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
        request(requestEntity, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_offen_oftenList, onRequestOftenListener);
    }

    String topCategoryId = "";

    public boolean bannerShow;
    public void initModels(HomeTopBean homeTopBean) {
        if(ptrFrameLayout!=null)
            ptrFrameLayout.refreshComplete();
        if (getActivity() == null) {
            return;
        }
        initRedBag(homeTopBean);
        items.clear();
        if(homeTopBean.getBanners()!=null&&homeTopBean.getBanners().size()>0) {
            items.add(0, homeTopBean);//topbanner
            bannerShow = true;
            Log.e("banner","true");
        }else {
            bannerShow = false;
            Log.e("banner","false");
        }
        items.add(new LinkedList<>());//functions,订单，配送中心。。。
        //vTips = layoutManager.getChildAt(1);

        if(homeTopBean.getMarketings()!=null) {
            for (int i = 0; i < homeTopBean.getMarketings().size(); i++) {
                Ad beanFlag = homeTopBean.getMarketings().get(i);
                if(beanFlag.getFunctionItem()==1){
                    items.add(beanFlag);
                }else{
                    if(beanFlag.getSeckillContent()!=null) {
                        if(beanFlag.getSeckillContent().getSeckillList()!=null&&beanFlag.getSeckillContent().getSeckillList().size()>1) {
                            HomeTop.SeckillBeanX.SeckillBean.SeckillListBean lastBean = new HomeTop.SeckillBeanX.SeckillBean.SeckillListBean();
                            lastBean.setPromotionId(beanFlag.getSeckillContent().getTotal());
                            beanFlag.getSeckillContent().getSeckillList().add(lastBean);
                            items.add(beanFlag.getSeckillContent());
                        }
                        else {
                            HomeTopBean.SecondsOne secondsOne = new HomeTopBean.SecondsOne();
                            secondsOne.goods = beanFlag.getSeckillContent();
                            items.add(secondsOne);
                        }
                    }
                }
            }
        }
        oftenTitle.setHaveMore(ViewBinderHomeOftenTitle.OFTENHAVE);
        items.add(oftenTitle);
        //items.add(ViewBinderHomeOftenTitle.OFTENHAVE);
/*
        //items.add(new HomeTop.SeckillBeanX());//homeTopBean.getSeckill());
        if(homeTopBean.getFreshest()==null||homeTopBean.getFreshest().size()==0) {
            items.add(0);
            multiAdapter.notifyDataSetChanged();
            return;
        }
        items.add(1);

        for(int i=0;i<homeTopBean.getFreshest().size();i++){
            HomeTopBean.FreshestBean bean = homeTopBean.getFreshest().get(i);
            if(bean.getBanner()==null||bean.getBanner().size()<=1){
                HomeTopBean.GoodsOne goodsOne = new HomeTopBean.GoodsOne();
                goodsOne.goods = bean;
                if(bean.getAds()!=null&&bean.getAds().size()>=1){
                    items.add(bean.getAds().get(0));//单图商品广告
                }
                items.add(goodsOne);//单图商品
            }else{
                HomeTopBean.GoodsMore goodsMore = new HomeTopBean.GoodsMore();
                goodsMore.goods = bean;
                if(bean.getAds()!=null&&bean.getAds().size()>=1){
                    items.add(bean.getAds().get(0));//多图商品广告
                }
                items.add(goodsMore);//多图商品
            }
            if(bean.getStore()!=null){
                HomeTopBean.FreshestBean.StoreBean storeBean = homeTopBean.getFreshest().get(i).getStore();
                if(storeBean.getFirst3()==null||storeBean.getFirst3().size()<=1){
                    HomeTopBean.StoreOne storeOne = new HomeTopBean.StoreOne();
                    storeOne.store = storeBean;
                    items.add(storeOne);
                }else{
                    HomeTopBean.StoreMore storeMore = new HomeTopBean.StoreMore();
                    storeMore.store = storeBean;
                    items.add(storeMore);
                }
            }
        }
        items.add(0);*/
        multiAdapter.notifyDataSetChanged();
        requestDc(true);

    }


    public void clearDc() {
        if (items!=null&&bannerShow&&items.size()>=2) {
            items.remove(1);
            items.add(1,new LinkedList<>());//functions,订单，配送中心。。。
            if (multiAdapter != null)
                multiAdapter.notifyDataSetChanged();
            return;
        }
        if (items!=null&&!bannerShow&&items.size()>=1) {
            items.remove(0);
            items.add(0,new LinkedList<>());//functions,订单，配送中心。。。
            if (multiAdapter != null)
                multiAdapter.notifyDataSetChanged();
            return;
        }
    }



    public void requestDc(boolean isSilent) {
        if (getActivity() != null) {
            RequestEntityMap re = new RequestEntityMap();
            re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_store_dcStores);
            RequestTag requestTag = new RequestTag();
            requestTag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_store_dcStores;
            if (isSilent) {
                requestTag.type = RequestTag.TYPE_CURRENT;
                requestTag.arg1 = "silent";
                int[] flag = {2, 3};

                re.putParameter("statuses", flag);
                re.putParameter("groupByMarket", false);
                re.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
                ApplicationHelper.getInstance().requestSilent(re, requestTag, onDetailRequestListener);
//                request(re, requestTag, onDetailRequestListener);
            } else {
                requestTag.arg1 = "1";
//                request(re, requestTag, onDetailRequestListener);
            }

        }
    }

    LinkedList<StoreDetail> dCList = new LinkedList();
    OnRequestListener<LinkedList<StoreDetail>> onDetailRequestListener = new OnRequestListener<LinkedList<StoreDetail>>() {

        public LinkedList<StoreDetail> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<LinkedList<StoreDetail>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            if (getActivity() != null) {
                hideProgressDialog();
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            if (getActivity() != null) {
                if (o1 != null && o1 instanceof RequestTag) {
                    RequestTag tag = (RequestTag) o1;
                    if ("silent".equals(tag.arg1)) {
                        clearDc();
                    } else {
                        hideProgressDialog();
                    }
                } else {
                    hideProgressDialog();
                }
            }
        }

        @Override
        public void onStart(Object o1) {
            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {
                } else {
                    showProgressDialog();
                }
            } else {
                showProgressDialog();
            }

        }

        @Override
        public void onResponse(ResponseEntity<LinkedList<StoreDetail>> responseEntity, Object o1) {
            if (getActivity() != null) {
                LinkedList<StoreDetail> responseElement = responseEntity.getResponseElement();
                dCList.clear();
                dCList.addAll(responseElement);
                if (items!=null&&bannerShow&&items.size()>=2) {
                    items.remove(1);
                    items.add(1, dCList);
                    multiAdapter.notifyDataSetChanged();
                    return;
                }
                if(items!=null&&!bannerShow&&items.size()>=1){
                    items.remove(0);
                    items.add(0, dCList);
                    multiAdapter.notifyDataSetChanged();
                    return;
                }
            }
        }
    };



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("________","requestCode"+""+requestCode);
        if(resultCode == 0x0404){//去问价>>全部商品
            ((HomeActivity)getAppActivity()).onTabSelect(1);
            return;
        }
        if(resultCode!= Activity.RESULT_OK) {
            return;
        }
        if (requestCode == 0x0303) {
            mHttpOftenLoad(0, false);
            if(getAppActivity() instanceof  HomeActivity){
                ((HomeActivity)getAppActivity()).freshAllGoods();
            }
            return;
        }
        mHttpLoad();
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {

            requestDc(true); //既然每次都刷新整个页面，又何必单独刷这个呢？？？

        }

        if (requestCode == 2 && resultCode == Activity.RESULT_OK) {
            Intent tv_bulk_load = new Intent(getActivity(),
                    MyOrderActivity.class);
            tv_bulk_load.putExtra("home_tab_index", 0);
            startActivity(tv_bulk_load);
        }
        if (requestCode == 3 && resultCode == Activity.RESULT_OK) {
            Intent tv_address = new Intent(getActivity(),
                    ReceiverAddressActivity.class);
            startActivity(tv_address);
        }
        if (requestCode == 4 && resultCode == Activity.RESULT_OK) {
            Intent attention = new Intent(getActivity(), ListStoreActivity.class);
            attention.putExtra("name", "我的关注");
            startActivity(attention);
        }
        if (requestCode == 11 && resultCode == Activity.RESULT_OK) {
            Intent tv_more = new Intent(getContext(),
                    CenterListActivity.class);
            startActivity(tv_more);
        }

    }


    public void onClick(View view) {
        Object o = view.getTag(R.id.item_key_position);

        Object t = view.getTag(R.id.item_key_id);
        Log.e("tag", "tag1:" + o);
        Log.e("tag", "tag2:" + t);
        String flag="";
        if (o != null && o instanceof String) {
            flag = (String) o;
            if (flag.equals("add")) {
                if (ApplicationHelper.getInstance().getUser().getAccess_token() == null || "".equals(ApplicationHelper.getInstance().getUser().getAccess_token())) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("relogin", true);
                    startActivityForResult(intent, 11);
                    return;
                }
                Intent tv_more = new Intent(getContext(),
                        CenterListActivity.class);
                startActivity(tv_more);
                return;
            } else if (!"notDc".equals(flag)) {
                //if (!isTipsVisible)
                    intoDeliveryStoreActivity(flag);
                return;
            }
        }
        switch (view.getId()) {
            case R.id.ll_address:

                MobclickAgent.onEvent(getContext(), "Click_Home_FourIcon");/*统计点击*/
                if (ApplicationHelper.getInstance().getUser().getAccess_token() == null || "".equals(ApplicationHelper.getInstance().getUser().getAccess_token())) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("relogin", true);
                    startActivityForResult(intent, 4);
                    return;
                }
                Intent tv_address = new Intent(getActivity(), ListStoreActivity.class);
                tv_address.putExtra("name", "我的关注");
                startActivity(tv_address);

/*                MobclickAgent.onEvent(getContext(), "Click_Home_FourIcon");*//*统计点击*//*
                if (ApplicationHelper.getInstance().getUser().getToken() == null || "".equals(ApplicationHelper.getInstance().getUser().getToken())) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("relogin", true);
                    startActivityForResult(intent, 3);
                    return;
                }
                Intent tv_address = new Intent(getActivity(),
                        ReceiverAddressActivity.class);
                startActivity(tv_address);*/
                break;
            case R.id.ll_pre:
                MobclickAgent.onEvent(getContext(), "Click_Home_FourIcon");/*统计点击*/
                Intent pre = new Intent(getActivity(), HomePreActivity.class);
                pre.putExtra("name", "预售商品");
                startActivity(pre);
                break;
            case R.id.tv_concern:
                MobclickAgent.onEvent(getContext(), "Click_Home_FourIcon");/*统计点击*/
                if (ApplicationHelper.getInstance().getUser().getAccess_token() == null || "".equals(ApplicationHelper.getInstance().getUser().getAccess_token())) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("relogin", true);
                    startActivityForResult(intent, 4);
                    return;
                }
                Intent attention = new Intent(getActivity(), ListStoreActivity.class);
                attention.putExtra("name", "我的关注");
                startActivity(attention);
                break;
            case R.id.ll_order:
                MobclickAgent.onEvent(getContext(), "Click_Home_FourIcon");/*统计点击*/
                if (ApplicationHelper.getInstance().getUser().getAccess_token() == null || "".equals(ApplicationHelper.getInstance().getUser().getAccess_token())) {
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("relogin", true);
                    startActivityForResult(intent, 2);
                    return;
                }
                Intent tv_my_order = new Intent(getActivity(),
                        MyOrderActivity.class);
                tv_my_order.putExtra("home_tab_index", 0);
                startActivity(tv_my_order);
                break;
            case R.id.ll_dc_flag://已绑定的配送中心
                MobclickAgent.onEvent(getContext(), "Click_Home_FourIcon");/*统计点击*/
                intoDeliveryStoreActivity(flag);
                break;
            case R.id.ll_more_store:
                Intent more_store = new Intent(getActivity(),
                        ListStoreActivity.class);
                startActivity(more_store);
                break;
            case R.id.ll_more_comm:
                Intent more_recommen = new Intent(getActivity(),
                        GoodsListActivity.class);
                //more_recommen.putExtra("isRecommended", 1);
//                more_recommen.putExtra("type", commsId);
                more_recommen.putExtra("type", "1");
                more_recommen.putExtra("title", "新品推荐");
                //普通布局,不带搜索
                more_recommen.putExtra("type_view", 1);
                more_recommen.putExtra("sortDirection", false);
                startActivity(more_recommen);
                break;
            case R.id.ll_more_activity:
                Intent more_activity = new Intent(getActivity(),
                        HomeSecondAreaActivity.class);
                startActivity(more_activity);
                break;
            case R.id.ll_more_pre:
                MobclickAgent.onEvent(getContext(), "Click_Home_FourIcon");/*统计点击*/
                Intent pre_more = new Intent(getActivity(), HomePreActivity.class);
                pre_more.putExtra("name", "预售商品");
                pre_more.putExtra("type", "2");
                startActivity(pre_more);
/*                Intent more_pre = new Intent(getActivity(),
                        GoodsListActivity.class);
                more_pre.putExtra("type", presId);
                more_pre.putExtra("isRecommended", -1);
                more_pre.putExtra("title", "预售商品");
                //普通布局,不带搜索
                more_pre.putExtra("type_view", 1);
                startActivity(more_pre);*/
                break;

        }
    }

    private void intoDeliveryStoreActivity(String id) {
        if (ApplicationHelper.getInstance().getUser().getAccess_token() == null || "".equals(ApplicationHelper.getInstance().getUser().getAccess_token())) {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            intent.putExtra("relogin", true);
            startActivityForResult(intent, 1);
            return;
        }
        requestSingleDc(false, id);

    }

    public void requestSingleDc(boolean isSilent, String id) {
        if (getActivity() != null) {
            RequestEntityMap re = new RequestEntityMap();
            re.putParameter("storeId", id);
            re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_store_dcStore);
            RequestTag requestTag = new RequestTag();
            requestTag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_store_dcStore;
            if (isSilent) {
                requestTag.type = RequestTag.TYPE_CURRENT;
                requestTag.arg1 = "silent";
                re.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
                ApplicationHelper.getInstance().requestSilent(re, requestTag, onDetailRequestListener2);
//                request(re, requestTag, onDetailRequestListener);
            } else {
                requestTag.arg1 = "1";
                request(re, requestTag, onDetailRequestListener2);
            }

        }
    }


    OnRequestListener<StoreDetail> onDetailRequestListener2 = new OnRequestListener<StoreDetail>() {
        @Override
        public StoreDetail jsonToObj(String s) {
            return new Gson().fromJson(s, StoreDetail.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            if (getActivity() != null) {
                hideProgressDialog();
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            if (getActivity() != null) {
                hideProgressDialog();
            }
        }

        @Override
        public void onStart(Object o1) {
            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    showProgressDialog();
                }
            } else {
                showProgressDialog();
            }

        }

        @Override
        public void onResponse(ResponseEntity<StoreDetail> responseEntity, Object o1) {
            if (getActivity() != null) {
                StoreDetail responseElement = responseEntity.getResponseElement();
                if (o1 != null && o1 instanceof RequestTag) {
                    RequestTag tag = (RequestTag) o1;
                    if ("silent".equals(tag.arg1)) {

                    } else {
                        hideProgressDialog();
                        intoDcPage(responseElement);
                    }
                } else {
                    hideProgressDialog();
                    intoDcPage(responseElement);
                }

            }
        }
    };


    public void intoDcPage(StoreDetail responseElement) {
        if (responseElement != null && getActivity() != null) {

//            if (!responseElement.isResult()) {
//                Intent tv_more = new Intent(getActivity(),
//                        CenterListActivity.class);//跳转到 配送中心列表
//                startActivity(tv_more);
//            } else {
                Intent tv_bulk_load = new Intent(getActivity(),
                        DcStoreActivity.class);//跳转到配送中心详情
                tv_bulk_load.putExtra("data", new Gson().toJson(responseElement));
                startActivity(tv_bulk_load);
//            }
        } else {

        }

    }




    View vTips;

    boolean isTipsVisible;

    public void showTips() {

        final SharedPreferences sp = getActivity().getSharedPreferences("tips_show" + ApplicationHelper.getInstance().getUser().getAccountId(), Context.MODE_PRIVATE);
/*        Log.e("isTopFragmentVisible",""+((HomeActivity) getAppActivity()).isTopFragmentVisible());
        Log.e("tips_number",""+sp.getInt("tips_number", 0));
        Log.e("vTips",""+vTips);// TODO: 2018/3/19*/
        //if (getAppActivity() != null && ((HomeActivity) getAppActivity()).isTopFragmentVisible() && vTips != null) {
        if (!isTipsVisible&&getAppActivity() != null && ((HomeActivity) getAppActivity()).isTopFragmentVisible() && 0 == sp.getInt("tips_number", 0) && vTips != null) {
            if (layoutManager != null) {
                layoutManager.scrollToPosition(0);
            }
            ptrFrameLayout.refreshComplete();
            ptrFrameLayout.setEnabled(false);
            layoutManager.setScrollEnabled(false);
            isTipsVisible = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (getActivity() == null || vTips == null) {
                        ptrFrameLayout.setEnabled(true);
                        layoutManager.setScrollEnabled(true);
                        isTipsVisible = false;
                        return;
                    }
                    View v = getActivity().findViewById(Window.ID_ANDROID_CONTENT);
                    if (v == null) {
                        ptrFrameLayout.setEnabled(true);
                        layoutManager.setScrollEnabled(true);
                        isTipsVisible = false;
                        return;
                    }
                    View p = ((ViewGroup) v).getChildAt(0);
                    if (p == null) {
                        ptrFrameLayout.setEnabled(true);
                        layoutManager.setScrollEnabled(true);
                        isTipsVisible = false;
                        return;
                    }
                    //SharedPreferences sp = getActivity().getSharedPreferences("tips_show" + ApplicationHelper.getInstance().getUser().getAccountId(), Context.MODE_PRIVATE);
/*                    int top = 0;
                    try {
                        Rect rtLocation = ViewUtils.getLocationInView(p, vTips);
                        top = rtLocation.top;
                        //Log.e("top",top);
                    } catch (Exception e) {
                        layoutManager.setScrollEnabled(true);
                        e.printStackTrace();
                        return;
                    }*/

                    //View vT = vTips.findViewById(R.id.viewpager_dc);


                    if (getAppActivity() != null && ((HomeActivity) getAppActivity()).isTopFragmentVisible() && 0 == sp.getInt("tips_number", 0) && !ptrFrameLayout.isRefreshing()) {
                        //if (vT != null && top > 20 && getAppActivity() != null && ((HomeActivity) getAppActivity()).isTopFragmentVisible() && 0 == sp.getInt("tips_number", 0) && !ptrFrameLayout.isRefreshing()) {
                        if (layoutManager != null)
                            layoutManager.scrollToPosition(0);
                        ptrFrameLayout.refreshComplete();

                        //isTipsVisible = true;
                        HighLightGuideView hg = HighLightGuideView.builder(getActivity())
                                .setBorderWidth(0)
                                .addHighLightGuidView(vTips, R.mipmap.tip_gesture)
                                .setHighLightStyle(HighLightGuideView.VIEWSTYLE_RECT);
                        hg.show();
                        hg.setOnDismissListener(new HighLightGuideView.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                isTipsVisible = false;
                            }
                        });
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putInt("tips_number", 1);
                        editor.commit();

                    } else {
                        isTipsVisible = false;
                    }
                    ptrFrameLayout.setEnabled(true);

                    layoutManager.setScrollEnabled(true);

                }
            }, 30 );
        }
    }


    public void initRedBag(HomeTopBean bean) {
/*            if(!"31".equals(ApplicationHelper.getInstance().getCity().getCityId())){
                Log.e("redBag","非上海不显示过红包弹框");
                return;
            }*/
        SharedPreferences sp = FileUtil.getSharedPreferences();
        Date now = new Date();
        String timeFlag = "" + now.getYear() + now.getMonth() + now.getDay();
        if (sp.getString("redFlag", "0").equals(timeFlag)) {
            Log.e("redBag", timeFlag + "今天已经显示过红包弹框");
            return;
        }
        SharedPreferences.Editor edit = sp.edit();
        if(bean.getBanners()==null)
            return;
        for (int i = 0; i < bean.getBanners().size(); i++) {//http://m.epfresh.com/purchase/red_packet.html?type=_share_
            if (bean.getBanners().get(i).getLink().contains("num=1706001")) {//"red_packet.html?num=1706001")){
                if (getActivity() != null) {
                    showRedBagDialog(i);
                    edit.putString("redFlag", "" + now.getYear() + now.getMonth() + now.getDay());
                    edit.commit();
                    return;
                }
            }
        }
    }

    CustomDialogRedBag.Builder builderRedBag;

    public void showRedBagDialog(final int position) {
        if (builderRedBag == null)
            builderRedBag = new CustomDialogRedBag.Builder(getContext());
        builderRedBag.setPositiveButton(new DialogInterface.OnClickListener() {//添加确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                Intent redBag = new Intent(getActivity(), WebActivity.class);
                Ad ad = homeTopBean.getBanners().get(position);
                if(getUser()!=null&&getUser().getAccess_token()!=null){
                    redBag.putExtra(Constant.KEY_WEB_URL, ad.getLink()+"&phone="+getUser().getPhone()+"&token="+getUser().getAccess_token()+"&cid=" + AppUtils.getUniquePsuedoID());
                    Log.e("top after login",ad.getLink()+"&phone="+getUser().getPhone()+"&token="+getUser().getAccess_token()+"&cid=" + AppUtils.getUniquePsuedoID());
                }
                else{
                    redBag.putExtra(Constant.KEY_WEB_URL, ad.getLink()+"&phone=unlogin");
                    Log.e("top unlogin",ad.getLink()+"&phone=unlogin");
                }
                redBag.putExtra(Constant.KEY_WEB_TITLE, ad.getTitle());
                redBag.putExtra("share_web", ad.getLink());
                redBag.putExtra("image_url", ad.getImg());
                redBag.putExtra("share_type", 1);
                redBag.putExtra("share_content", ad.getContent());
                MobclickAgent.onEvent(getContext(), "Click_Home_Banner");/*统计广告点击*/
                Log.e("redbagDialog:","KEY_WEB_URL:"+redBag.getStringExtra(Constant.KEY_WEB_URL)+"\nshare_web:"+redBag.getStringExtra("share_web")+"\nshare_content:"+redBag.getStringExtra("share_content")+"");


                startActivity(redBag);
                dialog.dismiss();
            }
        });
        builderRedBag.setNegativeButton(new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
                dialog.dismiss();
            }

        });
        builderRedBag.create().show();
        return;
    }
    @Override
    public void onCountDownListener(boolean isFinish){
        if(isFinish == true){
            mHttpLoad();
        }
    }




/*    *
     * 判断是否需要完善信息
     */
    public void isCompleted() {
        if(ApplicationHelper.getInstance().getUser().getAccess_token()==null) {
            return;
        }
        final RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_account_acc_isCompleted);
        RequestTag requestTag = new RequestTag();
        request(requestEntity, requestTag, new OnRequestListener<ResultBean>() {
            @Override
            public ResultBean jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, ResultBean.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
            }

            @Override
            public void onStart(Object tag) {
            }

            @Override
            public void onResponse(ResponseEntity<ResultBean> response, Object tag) {
                ResultBean responseElement = response.getResponseElement();
                Log.e("new perfect info","is complete");

                if (!responseElement.isResult()) {
                    Intent complete = new Intent(getContext(), PerfectInfoActivity.class);
                    complete.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(complete);
                    //finish();
                }

            }
        });
    }



    public void requestCount() {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_cnt);

//        re.putParameter("storeId", storeDetail.getId());
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        //首页已绑定用户，常购清单只看到散货；未绑定用户，只看到整货，且有比价问价 1整货 2散货
        int type;
        if(homeGoodsOften!=null&&homeGoodsOften.isAccountIsBindDc()){
            type = 2;
        }else {
            type = 1;
        }
        re.putParameter("wholeSalesType", type);
        ApplicationHelper.getInstance().requestSilent(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_cnt, onCartCntRequestListener);
    }

    OnRequestListener<CarCntResponse> onCartCntRequestListener = new OnRequestListener<CarCntResponse>() {
        @Override
        public CarCntResponse jsonToObj(String s) {
            return new Gson().fromJson(s, CarCntResponse.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<CarCntResponse> responseEntity, Object o) {
//            dcCnt = responseEntity.getResponseElement();
            carCntResponse = responseEntity.getResponseElement();
            if (carCntResponse != null) {
                carCntResponse.init();
            }
            updateCnt();
        }
    };

    CarCntResponse carCntResponse;

    public void updateCnt() {

        if (carCntResponse != null) {

            if (items != null) {
                for (int i = 0; i < items.size(); i++) {
                    if(items.get(i) instanceof HomeGoodsOften.ContentBean ){
                        HomeGoodsOften.ContentBean item = (HomeGoodsOften.ContentBean)items.get(i);
                        if (cartHelper != null && cartHelper.isRequesting(item.getUniqueKey())) {
                            Log.e("continue", "cnt:down");
                            continue;
                        }else {
                        }
                        item.setShoppingCarProductCount(carCntResponse.getGoodsCount(item.getIdPlus()));
                        //Log.e("listGoods", "cnt:" + item.getCount() + "---id:" + item.getId());
                        item.setShoppingCarId(carCntResponse.getShopingCarId(item.getIdPlus()));
                        if (carCntResponse != null && carCntResponse.getMerMsgMap() != null) {
                            item.setMsg(carCntResponse.getMerMsgMap().get(item.getShoppingCarId()));
                        }
/*                        ArrayList<HomeGoodsOften.ContentBean> list = (ArrayList<HomeGoodsOften.ContentBean>) items.get(i);
                        for(int j=0;j<list.size();j++){
                            HomeGoodsOften.ContentBean item = list.get(j);
                            if (cartHelper != null && cartHelper.isRequesting(item.getUniqueKey())) {
                                Log.e("continue", "cnt:down");
                                continue;
                            }else {
                            }
                            item.setShoppingCarProductCount(carCntResponse.getGoodsCount(item.getIdPlus()));
                            //Log.e("listGoods", "cnt:" + item.getCount() + "---id:" + item.getId());
                            item.setShoppingCarId(carCntResponse.getShopingCarId(item.getIdPlus()));
                            if (carCntResponse != null && carCntResponse.getMerMsgMap() != null) {
                                item.setMsg(carCntResponse.getMerMsgMap().get(item.getShoppingCarId()));
                            }
                        }*/


                    }
                }
            }

            if (multiAdapter != null) {
                multiAdapter.notifyDataSetChanged();
            }
        }

    }


    CartHelper cartHelper = new CartHelper();




    public void openDialog(final HomeGoodsOften.ContentBean cartGood) {

        final Dialog dialog = new Dialog(getContext(), R.style.no_title_dialog);

        dialog.setContentView(R.layout.dialog_cart_add);
        ImageView ivAdd = (ImageView) dialog.findViewById(R.id.iv_add);
        ImageView ivRemove = (ImageView) dialog.findViewById(R.id.iv_remove);

        final EditText ed = (EditText) dialog.findViewById(R.id.ed_price);

        ed.setText(FormatUtil.subZeroAndDot(cartGood.getCount() + ""));
        ed.setSelection(ed.length());
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 999999;
        ed.setFilters(new InputFilter[]{cashierInputFilter});
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = ed.getText().toString();
                double min = cartGood.getMoq();
                double incr = cartGood.getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                double amount = cnt;


                if (FormatUtil.remainderZero(amount, cartGood.getInventory()) > 0) {
                    amount = cartGood.getInventory();
                }

                amount = FormatUtil.countAdd(amount, incr);
                if (FormatUtil.remainderZero(amount, cartGood.getInventory()) > 0) {
                    amount = cartGood.getInventory();
                }


                cartGood.setShoppingCarProductCount(amount);
                ed.setText(FormatUtil.subZeroAndDot(amount + ""));
                ed.setSelection(ed.length());
            }
        });
        ivRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = ed.getText().toString();
                double min = cartGood.getMoq();
                double incr = cartGood.getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                double amount = cnt;
                if (amount < cartGood.getMoq()) {
                    amount = cartGood.getMoq();
                }

                amount = FormatUtil.countSubtract(amount, incr);
                if (amount < cartGood.getMoq()) {
                    amount = cartGood.getMoq();
                }
                cartGood.setShoppingCarProductCount(amount);
                ed.setText(FormatUtil.subZeroAndDot(amount + ""));
                ed.setSelection(ed.length());
            }
        });
        dialog.findViewById(R.id.negativeButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) getAppActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.positiveButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                double productCount = cartGood.getCount();
                String s = ed.getText().toString();
                double min = cartGood.getMoq();
                double incr = cartGood.getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                if (cnt < 0.01 || cnt < min) {
                    T.toast("不能少于" + FormatUtil.subZeroAndDot(min + ""));
                    cnt = FormatUtil.countFormat(cnt, incr, min);
                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }


                if (cnt > cartGood.getInventory()) {
                    T.toast("超过库存");
                    cnt = FormatUtil.countFormat(cartGood.getInventory(), incr, min);

                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }
                incr = incr < 0.01 ? min : incr;

                if (FormatUtil.isRemainder(cnt, incr, min)) {
                    cnt = FormatUtil.countFormat(cnt, incr, min);
                    Log.e("cnt:", "cnt:" + FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }

//                cartGood.setShoppingCarProductCount(cnt);
                reqCartCnt(cnt, cartGood);
                multiAdapter.notifyDataSetChanged();
                InputMethodManager imm = (InputMethodManager) getAppActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
                dialog.dismiss();
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {

            }
        });

        dialog.show();

    }

    public void addCartCnt(View v,HomeGoodsOften.ContentBean goods, boolean isAdd) {
        double min = goods.getMoq();
        double incr = goods.getIncr();
        double amount = goods.getCount();


        if (isAdd) {
            amount = FormatUtil.countAdd(amount, incr);
        } else {
            amount = FormatUtil.countAdd(amount, -incr);
        }

        if (FormatUtil.remainderZero(amount, goods.getInventory()) > 0) {
            amount = goods.getInventory();
            T.toast("库存不够");
        }else{
            if(isAdd)
                addAnim(v);
        }
        if (isAdd && FormatUtil.remainderZero(amount, goods.getMoq()) < 0) {
            amount = min;
        }


        if (!isAdd && (FormatUtil.remainderZero(amount, 0) <= 0 || FormatUtil.remainderZero(amount, min) < 0)) {
            amount = 0;
            reqCartCnt(amount, goods);
            return;
        }

//        amount = FormatUtil.countFormat(amount, incr, min);
        amount = FormatUtil.countFormat(amount, incr, min, goods.getInventory());
        reqCartCnt(amount, goods);

    }
// instanceof HomeGoodsOften.ContentBean)
    public void reqCartCnt(double productCount, HomeGoodsOften.ContentBean goods) {
        if (goods == null) {
            return;
        }
        goods.setShoppingCarProductCount(productCount);
        multiAdapter.notifyDataSetChanged();
        if (!cartHelper.checkIsCartRequesting(goods)) {
            updateCartCnt(productCount, goods);
        } else {

        }
    }

    public void responseCartCnt(boolean isFail, HomeGoodsOften.ContentBean goods, double cnt) {
        if (isFail) {
            cartHelper.responseCartFail(goods);
        } else {
            cartHelper.responseCartSuccess(goods, cnt);
        }
    }

    public void updateCartCnt(double productCount, HomeGoodsOften.ContentBean goods) {

        double count = goods.getShoppingCarProductCount();

        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_add);
/*        re.putParameter("promotionItemId", goods.getPromotionItemId());
*//*        if(goods.getOfferProductDto()!=null){
            re.putParameter("mainProductId",goods.getOfferProductDto().getOfferProductId());
        }*//*
        re.putParameter("shoppingCarId", goods.getShoppingCarId());
        re.putParameter("productUnitPrice", goods.getPriceOnly());
        re.putParameter("productId", goods.getId());
        re.putParameter("salesType", goods.getType());
        re.putParameter("versionId", goods.getLastSnapshotId());
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("productCount", productCount);
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());*/
        re.putParameter("specId", goods.getId());
        re.putParameter("count", productCount);
        RequestTag tag = new RequestTag();
        tag.tag = goods;
//        tag.tag = "appOrder/updateShoppingCarProductCount";
        tag.arg1 = productCount + "";
        tag.arg2 = count;
//        tag.arg2 = goods;
        if (cartHelper != null && goods !=null){
            cartHelper.updateRequest(goods.getUniqueKey());
        }
        request(re, tag, onCntRequestListener);
    }

    OnRequestListener<AddCarResponse> onCntRequestListener = new OnRequestListener<AddCarResponse>() {
        @Override
        public AddCarResponse jsonToObj(String s) {
            return new Gson().fromJson(s, AddCarResponse.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
            RequestTag tag = null;
            if (o1 instanceof RequestTag) {
                tag = (RequestTag) o1;
                String arg1 = tag.arg1;
                Object arg2 = tag.arg2;
                Object o2 = tag.tag;
                if (arg1 != null && o2 != null && o2 instanceof HomeGoodsOften.ContentBean) {
                    HomeGoodsOften.ContentBean goods = (HomeGoodsOften.ContentBean) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (arg2 != null && arg2 instanceof Double) {
//                        goods.setShoppingCarProductCount((Double) arg2);
                        responseCartCnt(true, goods, -1);
                        multiAdapter.notifyDataSetChanged();

                        T.toast(goods.getTitle() + " 添加购物车失败");
                    }
                }
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            hideProgressDialog();
            RequestTag tag = null;
            if (i / 10 == 40) {
                T.toast(o + "");
            }
            if (o1 instanceof RequestTag) {
                tag = (RequestTag) o1;
                String arg1 = tag.arg1;
                Object arg2 = tag.arg2;
                Object o2 = tag.tag;
                if (arg1 != null && o2 != null && o2 instanceof HomeGoodsOften.ContentBean) {
                    HomeGoodsOften.ContentBean goods = (HomeGoodsOften.ContentBean) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (arg2 != null && arg2 instanceof Double) {
//                        goods.setShoppingCarProductCount((Double) arg2);
                        responseCartCnt(true, goods, -1);
                        multiAdapter.notifyDataSetChanged();

                        if (i / 100 != 4) {
                            T.toast(goods.getTitle() + " 添加购物车失败");
                        }
                    }
                }
            }
        }

        @Override
        public void onStart(Object o) {
            //showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<AddCarResponse> responseEntity, Object o) {
            hideProgressDialog();
            AddCarResponse responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {

                RequestTag tag = null;
                if (o instanceof RequestTag) {
                    tag = (RequestTag) o;
                    String arg1 = tag.arg1;
                    Object o2 = tag.tag;
                    if (arg1 != null && o2 != null && o2 instanceof HomeGoodsOften.ContentBean) {
                        HomeGoodsOften.ContentBean goods = (HomeGoodsOften.ContentBean) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                        //goods.setShoppingCarProductCount(responseElement.getProductCnt());
                        goods.setShoppingCarId(responseElement.getShoppingCarId());
//                        DataManager.getInstance().setCartCntStatus(responseElement.getshoppingCarCnt());
                        DataManager.getInstance().updateCartCnt();
                        if(responseElement.getshoppingCarCnt()==0){
                            oftenTitle.setHasRedRound(false);
                        }else {
                            oftenTitle.setHasRedRound(true);
                        }
                        multiAdapter.notifyItemChanged(items.indexOf(oftenTitle));
                        responseCartCnt(false, goods, responseElement.getProductCnt());
                        if (carCntResponse == null) {
                            multiAdapter.notifyDataSetChanged();
                        } else {
                            carCntResponse.putCategoryCount(responseElement.getCategoryId(), responseElement.getCategoryCnt());
                            carCntResponse.putTopCategoryCount(responseElement.getTopCategoryId(), responseElement.getTopCategoryCnt());
                            carCntResponse.putPromotionCount(responseElement.getTopCategoryId(), responseElement.getPromotionCnt());
                            carCntResponse.putGoodsCount(goods.getIdPlus(), goods.getCount());
                            carCntResponse.putShopingCarId(goods.getIdPlus(), responseElement.getShoppingCarId());
                            if(responseElement.getProductCnt()==0){
                                carCntResponse.getMerMsgMap().remove(responseElement.getShoppingCarId());
                            }
                            updateCnt();
                        }
                    }
                }


            }
        }
    };

    View shoppingCartView;
    ViewGroup mainLayout;
//    View lvCart;


    private void initCartView() {
        AppActivity appActivity = getAppActivity();
        if (appActivity instanceof HomeActivity) {
            shoppingCartView = ((HomeActivity) appActivity).getCartView();
            mainLayout = ((HomeActivity) appActivity).getMainView();
//            lvCart = lvProduct;
        }
    }


    public void addAnim(View view) {
        int[] addLocation = new int[2];
        int[] cartLocation = new int[2];
//        int[] lvCartLocation = new int[2];
        view.getLocationInWindow(addLocation);
        shoppingCartView.getLocationInWindow(cartLocation);
//        lvCart.getLocationInWindow(lvCartLocation);

        PointF startP = new PointF();
        PointF endP = new PointF();
        PointF controlP = new PointF();

        startP.x = addLocation[0];
        startP.y = addLocation[1];
        endP.x = cartLocation[0] + LocalDisplay.dp2px(10);
        endP.y = cartLocation[1] - getAppActivity().getResources().getDimensionPixelSize(R.dimen.bottom_nav_ic_height);
        controlP.x = endP.x;
        controlP.y = startP.y;
        Log.e("location", "s===============");
        Log.i("location", "sw:" + LocalDisplay.SCREEN_WIDTH_PIXELS);
        Log.i("location", "sh:" + LocalDisplay.SCREEN_HEIGHT_PIXELS);
        Log.i("location", "sx:" + startP.x);
        Log.i("location", "sy:" + startP.y);
        Log.i("location", "ex:" + endP.x);
        Log.i("location", "ey:" + endP.y);
        Log.e("location", "e===============");

        final FakeAddImageView fakeAddImageView = new FakeAddImageView(getAppActivity());
        mainLayout.addView(fakeAddImageView);
        fakeAddImageView.setImageResource(R.drawable.cart_bezier);
        fakeAddImageView.getLayoutParams().width = LocalDisplay.dp2px(10);
        fakeAddImageView.getLayoutParams().height = LocalDisplay.dp2px(10);
        fakeAddImageView.setVisibility(View.VISIBLE);
        ObjectAnimator addAnimator = ObjectAnimator.ofObject(fakeAddImageView, "mPointF",
                new PointFTypeEvaluator(controlP), startP, endP);
        addAnimator.setInterpolator(new AccelerateInterpolator());
        addAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                fakeAddImageView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                fakeAddImageView.setVisibility(View.GONE);
                mainLayout.removeView(fakeAddImageView);
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        ObjectAnimator scaleAnimatorX = new ObjectAnimator().ofFloat(shoppingCartView, "scaleX", 0.6f, 1.0f);
        ObjectAnimator scaleAnimatorY = new ObjectAnimator().ofFloat(shoppingCartView, "scaleY", 0.6f, 1.0f);
        scaleAnimatorX.setInterpolator(new AccelerateInterpolator());
        scaleAnimatorY.setInterpolator(new AccelerateInterpolator());
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(scaleAnimatorX).with(scaleAnimatorY).after(addAnimator);
        animatorSet.setDuration(340);
        animatorSet.start();

    }


    public void requestDelete(HomeGoodsOften.ContentBean goods) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_often_delete);
        re.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
//        re.putParameter("productId", goods.getId());
        re.putParameter("productSpecId", goods.getId());
/*        if(goods.getOfferProductDto()!=null){
            Log.e("mainProductId",""+goods.getOfferProductDto().getMainProductId());
            re.putParameter("mainProductId",goods.getOfferProductDto().getMainProductId());
        }*/
        ApplicationHelper.getInstance().requestSilent(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_often_delete, onDeleteRequestListener);
    }


    OnRequestListener<ResultStringBean> onDeleteRequestListener = new OnRequestListener<ResultStringBean>() {
        @Override
        public ResultStringBean jsonToObj(String s) {
            return new Gson().fromJson(s, ResultStringBean.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<ResultStringBean> responseEntity, Object o) {
            if(getAppActivity() instanceof  HomeActivity){
                ((HomeActivity)getAppActivity()).freshAllGoods();
            }
/*            if(items!=null) {
                for (int i=0;i<items.size();i++){
                    if(items.get(i) instanceof HomeGoodsOften.ContentBean){
                        return;
                    }
                }
            }
            topCategoryId = "";*/
        }
    };



    MsgDialog msgDialog;
    String msgNow;

    private void openMsgDialog(HomeGoodsOften.ContentBean goods, List<String> list) {
        //if (msgDialog == null)
            msgDialog = new MsgDialog(getAppActivity());
        msgDialog.setOnCommitListener(new MsgDialog.OnCommitListener() {
            @Override
            public void onCommit(String msg, String goodsId) {
                msgDialog.dismiss();
                msgNow = msg;
                saveMsg(msg, goodsId);
            }
        });
        msgDialog.show(goods.getShoppingCarId(), list, goods.getMsg());
    }

    OnRequestListener<Map<String, Object>> onSaveMsgRequestListener = new OnRequestListener<Map<String, Object>>() {
        @Override
        public Map<String, Object> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<Map<String, Object>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            T.toast(o + "");//arg + ",请点击重试"
        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<Map<String, Object>> responseEntity, Object o) {
            hideProgressDialog();
            if (msgDialog != null)
                msgDialog.dismiss();

            Map<String, Object> responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                Object success = responseElement.get("success");
                if (success != null && success instanceof Boolean && ((Boolean) success)) {
/*                    groupList.get(msgPosition/1000).getResult().get(msgPosition%1000).setMerMsg(msgNow);
                    adapter.notifyDataSetChanged();*/
                    requestCount();
                }
            }
        }
    };

    public void saveMsg(String msg, String goodsId) {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_saveMsg);
        re.putParameter("merMsg", msg);
        re.putParameter("shoppingCarId", goodsId);
        ApplicationHelper.getInstance().requestSilent(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_saveMsg, onSaveMsgRequestListener);
    }



    RequestTag tag;
    public void requestFastMerTagList(HomeGoodsOften.ContentBean cartGood) {

        if (cartGood == null) {
            return;
        }
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_message_findByProductId);
        re.putParameter("productId", cartGood.getId());

        tag = new RequestTag();
        tag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_message_findByProductId;
        tag.arg2 = cartGood;
        tag.type = RequestTag.TYPE_CURRENT;
        request(re, tag, onRequestFastMerTagListener);
    }

    OnRequestListener<List<String>> onRequestFastMerTagListener = new OnRequestListener<List<String>>() {
        @Override
        public List<String> jsonToObj(String s) {
            return new Gson().fromJson(s, new TypeToken<List<String>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
            if (o1 != null && o1 instanceof RequestTag) {

                RequestTag tag = (RequestTag) o1;
                Object arg2 = tag.arg2;
                if (arg2 != null && arg2 instanceof HomeGoodsOften.ContentBean) {

                    openMsgDialog((HomeGoodsOften.ContentBean) arg2, null);
                }
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            hideProgressDialog();
            if (o1 != null && o1 instanceof RequestTag) {

                RequestTag tag = (RequestTag) o1;
                Object arg2 = tag.arg2;
                if (arg2 != null && arg2 instanceof HomeGoodsOften.ContentBean) {

                    openMsgDialog((HomeGoodsOften.ContentBean) arg2, null);
                }
            }

        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();


        }

        @Override
        public void onResponse(ResponseEntity<List<String>> responseEntity, Object o) {

            hideProgressDialog();
            List<String> responseElement = responseEntity.getResponseElement();
            if (responseElement != null && responseElement.size() > 0) {

            }
            if (o != null && o instanceof RequestTag) {

                RequestTag tag = (RequestTag) o;
                Object arg2 = tag.arg2;
                if (arg2 != null && arg2 instanceof HomeGoodsOften.ContentBean) {

                    openMsgDialog((HomeGoodsOften.ContentBean) arg2, responseElement);
                }
            }
        }
    };


}
